import 'antd/dist/antd.less'
import React, { useEffect, useMemo, useState } from 'react'
import ReactDOM from 'react-dom'
import { ConfigProvider } from 'antd'
import zhCN from 'antd/lib/locale/zh_CN'
import enUS from 'antd/lib/locale/en_US'
import 'moment/locale/zh-cn'
import {
  Designer,
  DesignerToolsWidget,
  ViewToolsWidget,
  Workspace,
  OutlineTreeWidget,
  ResourceWidget,
  HistoryWidget,
  StudioPanel,
  CompositePanel,
  WorkspacePanel,
  ToolbarPanel,
  ViewportPanel,
  ViewPanel,
  SettingsPanel,
  ComponentTreeWidget,
} from '@designable/react'
import {
  SettingsForm,
  setNpmCDNRegistry,
} from '@designable/react-settings-form'
import {
  createDesigner,
  GlobalRegistry,
  Shortcut,
  KeyCode,
} from '@designable/core'
import {
  LogoWidget,
  ActionsWidget,
  PreviewWidget,
  SchemaEditorWidget,
  MarkupSchemaWidget,
  BlocksResourceWidget,
} from './widgets'
import { saveSchema } from './service'
import {
  Form,
  Field,
  Input,
  Select,
  TreeSelect,
  Cascader,
  Radio,
  Checkbox,
  Slider,
  Rate,
  NumberPicker,
  Transfer,
  Password,
  DatePicker,
  TimePicker,
  Upload,
  Switch,
  Text,
  Card,
  ArrayCards,
  ObjectContainer,
  ArrayTable,
  Space,
  FormTab,
  FormCollapse,
  FormLayout,
  FormGrid,
  FormStep,
  ProTable,
  Dialog,
  Page,
  Result,
  Button,
  CustomAgreementForm,
  LabelTitle,
  UploadImage,
  ColorPicker,
  SuspendedBottom,
  BraftEditor,
  MultiLanguageDialog,
  GoodsCategorySelect,
  GoodsExchangeRestrictions,
  FixedDuration,
  AfterPurchaseFixedDuration,
  DetailContainer,
  Descriptions,
  FormMonthDayPicker,
  SingleCheckBox,
  CouponGoodsTableSelector,
  QRCode,
  Timeline,
  OrderHeader,
  DetailHeader,
  ButtonUploadExcel,
  SelectEquity,
  ArrayItems,
  DicProTable,
  ArrayTabs,
} from '../src'
import { IntlProvider } from 'react-intl'
import { getLanguagePackage } from '@designable/event-system'
import './global.less'
setNpmCDNRegistry('//unpkg.com')
import { setValidateLanguage } from '@formily/validator'

// 设置 moment 为中文
// moment.locale('zh-cn')

GlobalRegistry.registerDesignerLocales({
  'zh-CN': {
    sources: {
      Inputs: '输入控件',
      Layouts: '布局组件',
      Arrays: '自增组件',
      Displays: '展示组件',
    },
  },
  'en-US': {
    sources: {
      Inputs: 'Inputs',
      Layouts: 'Layouts',
      Arrays: 'Arrays',
      Displays: 'Displays',
    },
  },
  'ko-KR': {
    sources: {
      Inputs: '입력',
      Layouts: '레이아웃',
      Arrays: '배열',
      Displays: '디스플레이',
    },
  },
})

const locale = localStorage.getItem('umi_locale') || 'zh-CN'
const antdLocales = {
  'zh-CN': zhCN,
  'en-US': enUS,
}

const App = () => {
  const engine = useMemo(
    () =>
      createDesigner({
        shortcuts: [
          new Shortcut({
            codes: [
              [KeyCode.Meta, KeyCode.S],
              [KeyCode.Control, KeyCode.S],
            ],
            handler(ctx) {
              saveSchema(ctx.engine)
            },
          }),
        ],
        rootComponentName: 'Page', //根组件名称
      }),
    []
  )
  const [langPkg, setLangPkg] = useState([])
  const messages = useMemo(() => {
    return langPkg.find((item) => item.language === locale)?.locale
  }, [langPkg, locale])

  const getLangPkg = async () => {
    if (langPkg.length > 0) return
    try {
      const res = await getLanguagePackage('intl-web', 'main')
      setLangPkg(res)
    } catch (error) {
      // 静默处理错误
    }
  }
  useEffect(() => {
    // getLangPkg()
    // setValidateLanguage(locale)
    // registerValidateLocale({
    //   'zh-CN': {
    //     required: '必填',
    //   },
    //   'en-US': {
    //     required: 'Required',
    //   },
    // })
  }, [])
  return (
    <IntlProvider messages={messages} locale={locale}>
      <ConfigProvider locale={antdLocales[locale]}>
        <Designer engine={engine}>
          <StudioPanel logo={<LogoWidget />} actions={<ActionsWidget />}>
            <CompositePanel>
              <CompositePanel.Item title="panels.Component" icon="Component">
                <ResourceWidget
                  title="sources.Inputs"
                  sources={[
                    UploadImage,
                    Form,
                    Input,
                    Password,
                    NumberPicker,
                    Rate,
                    Slider,
                    Select,
                    TreeSelect,
                    Cascader,
                    Transfer,
                    Checkbox,
                    Radio,
                    DatePicker,
                    TimePicker,
                    Upload,
                    Switch,
                    ObjectContainer,
                    ColorPicker,
                    BraftEditor,
                    MultiLanguageDialog,
                    GoodsCategorySelect,
                    GoodsExchangeRestrictions,
                    FixedDuration,
                    AfterPurchaseFixedDuration,
                    FormMonthDayPicker,
                    SingleCheckBox,
                    ButtonUploadExcel,
                    SelectEquity,
                    CouponGoodsTableSelector,
                    DicProTable,
                  ]}
                />
                <ResourceWidget
                  title="sources.Layouts"
                  sources={[
                    SuspendedBottom,
                    LabelTitle,
                    Button,
                    Result,
                    Dialog,
                    ProTable,
                    CustomAgreementForm,
                    Card,
                    FormGrid,
                    FormStep,
                    FormTab,
                    FormLayout,
                    FormCollapse,
                    Space,
                    DetailContainer,
                    Descriptions,
                    QRCode,
                    Timeline,
                    OrderHeader,
                    DetailHeader,
                    DicProTable,
                    ArrayTabs,
                  ]}
                />
                <ResourceWidget
                  title="sources.Arrays"
                  sources={[ArrayCards, ArrayTable, ArrayItems]}
                />
                <ResourceWidget title="sources.Displays" sources={[Text]} />
              </CompositePanel.Item>
              <CompositePanel.Item title="panels.OutlinedTree" icon="Outline">
                <OutlineTreeWidget />
              </CompositePanel.Item>
              <CompositePanel.Item title="panels.History" icon="History">
                <HistoryWidget />
              </CompositePanel.Item>
              <CompositePanel.Item title="已保存的区块" icon="Module">
                <BlocksResourceWidget />
              </CompositePanel.Item>
            </CompositePanel>
            <Workspace id="form">
              <WorkspacePanel>
                <ToolbarPanel>
                  <DesignerToolsWidget />
                  <ViewToolsWidget
                    use={['DESIGNABLE', 'JSONTREE', 'MARKUP', 'PREVIEW']}
                  />
                </ToolbarPanel>
                <ViewportPanel style={{ height: '100%' }}>
                  <ViewPanel type="DESIGNABLE">
                    {() => (
                      <div
                        id="designable"
                        style={{
                          width: '100%',
                          height: '100%',
                          transform: 'translate(0, 0)',
                          position: 'relative',
                          paddingBottom: '80px',
                        }}
                      >
                        <ComponentTreeWidget
                          components={{
                            SelectEquity,
                            SuspendedBottom,
                            UploadImage,
                            Result,
                            Page,
                            Form,
                            Field,
                            Input,
                            Select,
                            TreeSelect,
                            Cascader,
                            Radio,
                            Checkbox,
                            Slider,
                            Rate,
                            NumberPicker,
                            Transfer,
                            Password,
                            DatePicker,
                            TimePicker,
                            Upload,
                            Switch,
                            Text,
                            Card,
                            ArrayCards,
                            ArrayTable,
                            ArrayItems,
                            Space,
                            FormTab,
                            FormStep,
                            FormCollapse,
                            FormGrid,
                            FormLayout,
                            ObjectContainer,
                            ProTable,
                            Dialog,
                            Button,
                            CustomAgreementForm,
                            LabelTitle,
                            ColorPicker,
                            BraftEditor,
                            MultiLanguageDialog,
                            GoodsCategorySelect,
                            GoodsExchangeRestrictions,
                            FixedDuration,
                            AfterPurchaseFixedDuration,
                            DetailContainer,
                            Descriptions,
                            FormMonthDayPicker,
                            SingleCheckBox,
                            CouponGoodsTableSelector,
                            QRCode,
                            Timeline,
                            OrderHeader,
                            DetailHeader,
                            ButtonUploadExcel,
                            DicProTable,
                            ArrayTabs,
                          }}
                        />
                      </div>
                    )}
                  </ViewPanel>
                  <ViewPanel type="JSONTREE" scrollable={false}>
                    {(tree, onChange) => (
                      <SchemaEditorWidget tree={tree} onChange={onChange} />
                    )}
                  </ViewPanel>
                  <ViewPanel type="MARKUP" scrollable={false}>
                    {(tree) => <MarkupSchemaWidget tree={tree} />}
                  </ViewPanel>
                  <ViewPanel type="PREVIEW">
                    {(tree) => <PreviewWidget tree={tree} />}
                  </ViewPanel>
                </ViewportPanel>
              </WorkspacePanel>
            </Workspace>
            <SettingsPanel title="panels.PropertySettings">
              <SettingsForm uploadAction="https://www.mocky.io/v2/5cc8019d300000980a055e76" />
            </SettingsPanel>
          </StudioPanel>
        </Designer>
      </ConfigProvider>
    </IntlProvider>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))
